package cn.xinfei.xdecision.engine.runner.context;

import cn.xinfei.xdecision.engine.runner.executor.NodeHandler;
import cn.xinfei.xdecision.engine.runner.metadata.MetadataProvider;
import cn.xinfei.xdecision.engine.runner.service.DecisionIdBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Data
@Service
public class XDecisionContextHolder {

    @Autowired
    private DecisionIdBuilder decisionIdBuilder;

    @Autowired
    protected MetadataProvider metadataProvider;

    public XDecisionContext cloneContext(XDecisionContext clone) {
        XDecisionContext.setContext(clone);
        XDecisionContext newContext = XDecisionContext.getContext();
//        PipelineContextHolder.setBranch(BranchTypeEnum.CHALLENGE.name());
//        PipelineContextHolder.putInContext("ChampionChallenge", "DeepCopy", "DeepCopy");
        String engineCode = PipelineContextHolder.getEngineCode();

        try {
            Map<String, NodeHandler> engineNodeMap = metadataProvider.getEngineNodeList(engineCode);
            newContext.getPipelineMetaInfoContext().putAll(engineNodeMap);

            String scene = newContext.getTpCode();
            String newDecisionId = decisionIdBuilder.create(scene);
            //更新decisionId
            log.info("产生新的newDecisionId={}",newDecisionId);
            PipelineContextHolder.setDecisionId(newDecisionId);
        } catch (Exception e) {
            //此异常严重，需要立即处理
            log.error("上下文深拷贝异常，context={},msg={}", PipelineContextHolder.toJson(), e.getMessage(), e);
        }

        return newContext;
    }


}
